#define  _CRT_SECURE_NO_WARNINGS
class Solution {
public:
    int minFallingPathSum(vector<vector<int>>& matrix) {
        int m = matrix.size(), n = matrix[0].size();
        vector<vector<int>> dp(m, vector<int>(n));
        for (int i = 0; i < n; i++) dp[0][i] = matrix[0][i];
        for (int i = 1; i < m; i++)
            for (int j = 0; j < n; j++)
            {
                int prev = dp[i - 1][j];
                if (j) prev = min(prev, dp[i - 1][j - 1]);
                if (j < n - 1) prev = min(prev, dp[i - 1][j + 1]);
                dp[i][j] = prev + matrix[i][j];
            }
        int ret = dp[m - 1][0];
        for (int i = 1; i < n; i++) ret = min(ret, dp[m - 1][i]);
        return ret;
    }
};